package com.fantasy.blog.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fantasy.blog.dao.mapper.ArticleMapper;
import com.fantasy.blog.dao.pojo.Article;
import com.fantasy.blog.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class ThreadService {


    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 更新
     * @param articleMapper
     * @param article
     */
    @Async("taskExecutor")
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {
        int viewCounts = article.getViewCounts();
        Article newArticle = new Article();
        newArticle.setWeight(article.getWeight());
        newArticle.setViewCounts(viewCounts + 1);

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

        /**
         * 线程安全，对于并发事件进行判断，若其他线程导致更新后，该数据将会变成旧数据
         * 此时应该停止更新
         */
        queryWrapper.eq(Article::getId,article.getId())
                    .eq(Article::getViewCounts,viewCounts);

        articleMapper.update(newArticle,queryWrapper);

    }

    /**
     *
     * @param articleId
     */
    @Async("taskExecutor")
    public void updateCommentCountById(Long articleId) {
        Article article = articleMapper.selectById(articleId);
        int commentCount = article.getCommentCounts();
        article.setCommentCounts(commentCount + 1);

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Article::getId,articleId)
                .eq(Article::getCommentCounts,commentCount);

        articleMapper.update(article,queryWrapper);
    }
}
